package mylibrary.security.RSA;

import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

public class Test {

	private static byte[] publicKey;
	private static byte[] privateKey;
	private static Map keyMap;

	
	public static void main(String[] args) throws Exception {
		
		Test test = new Test();
		test.initKey();
		
		String inputStr = "This is the test string";
		byte[] data = inputStr.getBytes();
		System.out.println("plain text=" + Base64.encodeBase64String(data));
		
		//encrypt with private key
//		byte[] encodedData = RSA.encryptByPrivateKey(data, test.privateKey);
//		System.out.println("encrypted text=" + Base64.encodeBase64String(encodedData));
//		byte[] decodedData = RSA.decryptByPublicKey(encodedData, test.publicKey);
//		System.out.println("decrypted text=" + Base64.encodeBase64String(decodedData));
		
		//encrypt with public key
//		byte[] encodedData = RSA.encryptByPublicKey(data, test.publicKey);
//		System.out.println("encrypted text=" + Base64.encodeBase64String(encodedData));
//		byte[] decodedData = RSA.decryptByPrivateKey(encodedData, test.privateKey);
//		System.out.println("decrypted text=" + Base64.encodeBase64String(decodedData));

		
		//sinature and verify
		Signature signature = Signature.getInstance("MD5WithRSA");
		signature.initSign((RSAPrivateKey)keyMap.get("RSAPrivateKey"));
		signature.update(data);
		byte[] sign = signature.sign();
		System.out.println("sign=" + Base64.encodeBase64String(sign));
		
		byte[] encodedData = RSACode.encryptByPrivateKey(data, privateKey);
		System.out.println("encrypted text=" + Base64.encodeBase64String(encodedData));
		
		
		Signature anotherSignature = Signature.getInstance("MD5WithRSA");
		anotherSignature.initVerify((RSAPublicKey)keyMap.get("RSAPublicKey"));
		anotherSignature.update("This is the test string".getBytes());
		boolean status = anotherSignature.verify(sign);
		System.out.println("Verify=" + status);
	}
	
	public static void initKey() throws Exception {
		keyMap = RSACode.initKey();
		publicKey = RSACode.getPublicKey(keyMap);
		privateKey = RSACode.getPrivateKey(keyMap);
		
		System.out.println("public key=" + Base64.encodeBase64String(publicKey));
		System.out.println("private key=" + Base64.encodeBase64String(privateKey));
	}
	
}
